import React, {Component} from 'react';
import { Route, Switch } from 'react-router-dom';
import routes from '../routes';

// 扩展子路由
function extendRoutes(routes, initRoute) {
    if(Object.prototype.toString.call(routes) !== '[object Array]' ||
        Object.prototype.toString.call(initRoute) !== '[object Array]'){
        console.warn('routes、initRoute：请传入数组');
        return false
    }
    routes.forEach(route => {
        if(route.routes){
            extendRoutes(route.routes, initRoute)
        }
        route.component && initRoute.push(route)
    })
}

const e_routes = [];
extendRoutes(routes, e_routes);

// 导出router
class RenderRouter extends Component{
    render() {
        return (
            <>
                <Switch>
                    {
                        e_routes.map(route => {
                            return (
                                <Route exact
                                       key={route.path}
                                       path={route.path}
                                       render={(props) => {
                                           document.title = route.meta.title;
                                           return <route.component {...props} />
                                       }}
                                />
                            )
                        })
                    }
                </Switch>
            </>
        )
    }
}

export default RenderRouter
